<template>
    <f7-page @page:beforein="pageBeforeIn">
        <f7-navbar>
            <f7-nav-left :back-link="true"></f7-nav-left>
            <f7-nav-title title="现场检查" :subtitle="batch && batch.name"></f7-nav-title>
            <f7-nav-right>
                <f7-link @click="openBatchList">
                    <span class="tabbar-label">切换批次</span>
                    <i class="icon material-icons">chevron_right</i>
                </f7-link>
            </f7-nav-right>
            <f7-subnavbar>
                <f7-toolbar tabbar>
                    <f7-link tab-link="#draft-list-tab" tab-link-active>
                        <span class="tabbar-label">草稿</span>
                    </f7-link>
                    <f7-link tab-link="#submited-list-tab">
                        <span class="tabbar-label">已提交</span>
                    </f7-link>
                </f7-toolbar>
            </f7-subnavbar>
        </f7-navbar>
        <f7-fab position="left-bottom" slot="fixed" text="问题登记" color="blue"
            @click="registOpen(null)"
            v-if="batch != null">
            <f7-icon material="add"></f7-icon>
        </f7-fab>
        <f7-fab position="right-bottom" slot="fixed" text="批量上传" color="yellow" 
            @click="problemBatchSubmitOpen" style="margin-left:57%;"
            v-if="isOnline">
            <f7-icon f7="arrow_up"></f7-icon>
        </f7-fab>
        <f7-tabs>
            <f7-tab id="draft-list-tab" tab-active>
                <f7-list media-list style="margin:0px;">
                    <f7-list-item chevron-center swipeout link="#"
                        v-for="(problem, i) in draftProblemList" :key="problem.tid"
                        :title="problemTitle(problem)"
                        :subtitle="problemSubtitle(problem)"
                        :text="problemText(problem)"
                        @click="registOpen(problem)"
                        @swipeout:deleted="draftProblemDelete(problem.tid)">
                        <img slot="media" width="80" height="80" :src="problemImage(problem)" />
                        <f7-swipeout-actions right>
                            <f7-swipeout-button delete confirm-title="" confirm-text="确定删除该记录？">删除</f7-swipeout-button>
                            <f7-swipeout-button v-if="isOnline" confirm-text="确定上传该记录？" 
                                @click="draftProblemSubmit(problem)">提交</f7-swipeout-button>
                        </f7-swipeout-actions>
                    </f7-list-item>
                </f7-list>
            </f7-tab>
            <f7-tab id="submited-list-tab">
                <ProblemList :task="task" :problems="submitedProblemList"></ProblemList>
            </f7-tab>
        </f7-tabs>
    </f7-page>
</template>

<script>
import networkEvent from '@/mixins/networkEvent';
import back from '@/mixins/back.js';
import localeCheck from '@/mixins/localeCheck.js';
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import FileUtil from "@/utils/FileUtil.js";
import events from 'events';
import store from '@/store';
import { getUser, setUser, clearUser } from '@/utils/auth';
import { getStore, setStore, clearStore } from '@/utils/storage';
import keys from '@/utils/rememberKeys';
import request from '@/utils/request';
import db from '@/utils/db';
import ProblemList from "../../../common/ProblemList";
import eventBus from '@/utils/eventBus.js';
export default {
    mixins: [networkEvent, back, localeCheck],
    store: store,
    components: {ProblemList},
    data: function() {
        return {
        	batchId: null,
            batch: null,
            draftProblemList: [],
            submitedProblemList: [],
            task: "local"
        }
    },
    methods: {
    	pageBeforeIn: function() {
    		var self = this;
            var sql = 
                "select t.id " +
                "from tb_checkquality_batch t " +
                "left join tb_bid_section p " +
                "on t.bid_section_id = p.id " +
                "where p.project_id = '" + getStore(keys.projectIdKey) + "' " +
                "and t.is_close = 0 " +
                "and (t.in_charge_by = '" + getUser().userId + "' or t.id in ( " +
                "    select batch_id from tb_batch_user where user_id = '" + getUser().userId + "' " +
                ")) ";
            Common.executeSql(sql, []).then(result => {
        		var batchId = getStore(keys.localeCheckBatchIdKey);
            	let rs = result.rs;
                var found = false;
                for(var i = 0; i < rs.rows.length; i++) {
                    var row = rs.rows.item(i);
                    if(batchId == row.id) {
                        found = true;
                        break;
                    }
                }
                //首次进入或者批次未找到
                if(!found) {
                	if(rs.rows.length > 0) {
                		batchId = rs.rows.item(0).id;
                	} else {
                		batchId = null;
                	}
                }
                self.batchId = batchId;
            }).catch(error => {
            	console.error(error);
            });
    	},
        openBatchList: function() {
            var self = this;
            var router = this.$f7router.navigate('/Workbench/LocaleCheck/BatchList');
            router.off('batchChanged');
            router.on('batchChanged', function(batchId) {
                self.batchId = batchId;
            });
        },
        registOpen: function(problem) {
            var self = this;
            self.$f7.preloader.show();
            new Promise((resolve, reject) => {
            	if(problem == null) {
            		let sql = "\
            		    insert into tmp_locale_check_checkquality_problem_regist( \
            		        batch_id, regist, repair_deadline, reinspects, ccs, \
            		        emergency_degree, building_id, unit_id, floor_id, \
            		        remark, repair, contractor_id, photos, problem_values \
            		    ) values ( \
            		        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? \
            		    ) \
            		";
                    var localeCheck = getStore(keys.localeCheckProblemRegistKey);
                    if(localeCheck == null || localeCheck.bidSectionId == null || 
                            localeCheck.bidSectionId != this.batch.bidSectionId) {
                        clearStore(keys.localeCheckProblemRegistKey);
                        localeCheck = {};
                        localeCheck.bidSectionId = this.batch.bidSectionId;
                        setStore(keys.localeCheckProblemRegistKey, localeCheck);
                    }
                    
            		let values = [];
            		values.push(self.batchId);
            		values.push(getUser().userId);
            		values.push(self.batch.repairDeadline);
            		values.push(JSON.stringify([getUser().userId]));
            		values.push(JSON.stringify(self.batch.ccs));
            		values.push('一般');
                    values.push(localeCheck.buildingId);
                    values.push(localeCheck.unitId);
                    values.push(localeCheck.floorId);
                    values.push('');
                    values.push('');
                    values.push('');
                    values.push('[]');
                    values.push('[]');
            		return Common.executeSql(sql, values).then(result => {
            			let rs = result.rs;
            			let tid = rs.insertId;
            			let sql = "\
            			    select * from tmp_locale_check_checkquality_problem_regist t \
            			    where t.tid = ? \
            			";
            			return Common.executeSql(sql, [tid]);
            		}).then(result => {
            			let rs = result.rs;
            			let row = rs.rows.item(0);
            			let problem = self.convertLocaleCheckDraft(row);
            			self.draftProblemList.push(problem);
            			resolve(problem);
            		}).catch(error => {
            			console.error(error);
            			reject(error);
            		});
            	} else {
            		setTimeout(() => {
                        resolve(problem);
            		}, 1000);
            	}
            }).then(problem => {
                var url = "/Workbench/LocaleCheck/ProblemRegist";
                var router = self.$f7router.navigate(url, {
                    props: {
                        batch: self.batch,
                        draftProblem: problem
                    }
                });
                router.off('saveTemporary');
                router.on('saveTemporary', function(tid) {
                    self.addDraftProblem(tid);
                });
                router.off('submitedProblem');
                router.on('submitedProblem', function(problemId) {
                    self.submitedProblem(problemId);
                });
                router.off('deleteDraftProblem');
                router.on('deleteDraftProblem', function(tid) {
                    for(var i = 0; i < self.draftProblemList.length; i++) {
                        if(tid == self.draftProblemList[i].tid) {
                            self.draftProblemDelete(self.draftProblemList[i].tid);
                            break;
                        }
                    }
                });
            }).catch(error => {
            	console.error(error);
            	self.$f7.preloader.hide();
            });
        },
        addDraftProblem: function(tid) {
            var self = this;
            window.db.transaction(function(tx) {
                var sql = "\
                    select * from tmp_locale_check_checkquality_problem_regist \
                    where tid = '" + tid + "' \
                ";
                tx.executeSql(sql, [], function(tx, rs) {
                    var draftProblem = self.convertLocaleCheckDraft(rs.rows.item(0));
                    for(var i = 0; i < self.draftProblemList.length; i++) {
                        if(self.draftProblemList[i].tid == draftProblem.tid) {
                            self.draftProblemList.splice(i, 1, draftProblem);
                            return;
                        }
                    }
                    self.draftProblemList.push(draftProblem);
                });
            }, function(error) {
                console.error(error);
            });
        },
        submitedProblem: function(problemId) {
            var self = this;
            window.db.transaction(function(tx) {
                var sql = 
                    "select e.bid_section_id, b.*, c.id as checkquality_repair_id, c.repair, " +
                    "  case when GROUP_CONCAT(d.reinspect) is null then '[]' else '[' || GROUP_CONCAT('\"' || d.reinspect || '\"') || ']' end as reinspect, " +
                    "  case when GROUP_CONCAT(d.reinspect) is null then '[]' else '[' || GROUP_CONCAT('\"' || d.id || '\"') || ']' end as checkquality_reinspect_id " +
                    "from tb_checkquality_problem b " +
                    "left join tb_checkquality_repair c on b.id = c.checkquality_problem_id " +
                    "left join tb_checkquality_reinspect d ON b.id = d.checkquality_problem_id " +
                    "left join tb_building e on e.id = b.building_id " +
                    "where b.id = '" + problemId + "' " +
                    "and c.child_checkquality_repair_id is null " +
                    "GROUP BY b.id order by b.regist_date desc";
                tx.executeSql(sql, [], function(tx, rs) {
                     var row = rs.rows.item(0);
                     let i = 0;
                     while(i < self.submitedProblemList.length) {
                    	 let problem = self.submitedProblemList[i++];
                    	 if(problem.id == row.id) {
                    		 break;
                    	 }
                     }
                     let problem = self.convertLocaleCheckSubmited(row)
                     if(i < self.submitedProblemList.length) {
                    	 self.submitedProblemList.splice(i, 1, problem);
                     } else {
                         let problemList = [];
                         problemList.push(problem);
                         self.submitedProblemList = problemList.concat(self.submitedProblemList);
                         // self.submitedProblemList.psush(problem);
                     }
                });
            }, function(error) {
                console.error(error);
            });
        },
        problemBatchSubmitOpen: function() {
            var self = this;
            var url = "/Workbench/LocaleCheck/ProblemRegistSubmit";
            var router = this.$f7router.navigate(url, {
                props: {
                    draftProblemList: this.draftProblemList,
                    batchId: self.batch.id
                }
            });
            router.off('submitedProblem');
            router.on('submitedProblem', function(problem) {
                self.submitedProblem(problem.id);
            });
            router.off('deleteDraftProblem');
            router.on('deleteDraftProblem', function(tid) {
                for(var i = 0; i < self.draftProblemList.length; i++) {
                    if(tid == self.draftProblemList[i].tid) {
                        self.draftProblemDelete(self.draftProblemList[i].tid);
                        break;
                    }
                }
            });
        },
       problemTitle: function(problem) {
            var title = '';
            if(problem.problemClassId != null) {
                var problemClass = this.$store.state.global.problemClassMap[problem.problemClassId];
                title = problemClass.problem_class_name;
                var parentProblemClassId = problemClass.parent_problem_class_id;
                if(parentProblemClassId != null) {
                    title = 
                        this.$store.state.global.problemClassMap[parentProblemClassId].problem_class_name +
                        ' - ' + title; 
                }
            }
            return title;
        },
      problemSubtitle: function(problem) {
            var subtitle = '';
            if(problem.problemId != null) {
                subtitle = this.$store.state.global.problemMap[problem.problemId].problem_name;
            }
            return subtitle;
        },
        problemText: function(problem) {
            var text = '';
            if(problem.registDate != null) {
                text += DateUtil.dateToStr('yyyy-MM-dd HH:mm', problem.registDate) + ' ';
            }
            if(problem.place != null) {
                text += problem.place;
            }
            return text;
        },
        problemImage: function(problem) {
            if(problem.imageFile && problem.imageFile.length > 0) {
                if(problem.smallImageFile && problem.smallImageFile.length > 0) {
                    return problem.smallImageFile[0].url;
                } else {
                    return problem.imageFile[0].url + "?x-oss-process=image/resize,m_fixed,h_80,w_80";
                }
            } else {
                return '';
            }
        },
        draftProblemDelete: function(tid) {
            var self = this;
            self.$f7.preloader.show();
            for(var i = 0; i < self.draftProblemList.length; i++) {
                if(tid == self.draftProblemList[i].tid) {
                    self.draftProblemList.splice(i, 1);
                    break;
                }
            }
            let sql = "\
                select * from tmp_locale_check_checkquality_problem_regist \
                where tid = '" + tid + "' \
            ";
            Common.executeSql(sql, []).then(result => {
            	let rs = result.rs;
            	if(rs.rows.length > 0) {
            		let problem = self.convertLocaleCheckDraft(rs.rows.item(0));
            		let promises = [];
            		let promise = null;
            		
            		let sql = "\
                        delete from tmp_locale_check_checkquality_problem_regist \
                        where tid = '" + problem.tid + "' \
                    ";
            		promise = Common.executeSql(sql, []);
            		promises.push(promise);
            		
                    problem.photos.forEach(photo => {
                        let promise = FileUtil.remove(photo);
                        promises.push(promise);
                    });
                    return Promise.all(promises);
            	} else {
            		return Promise.resolve();
            	}
            }).then(() => {
            	self.$f7.preloader.hide();
            }).catch(error => {
                console.error(error);
                self.$f7.dialog.alert('', '删除草稿失败');
                self.$f7.preloader.hide();
            });
        },
        draftProblemSubmit: function(draftProblem) {
            if(!Common.isOnline()) {
                this.$f7.dialog.alert('', '当前网络信号较弱，请稍后再提交!');
                return;
            }
            if(draftProblem.problemClassId == null) {
                this.$f7.dialog.alert('', '请选择检查项!');
                return;
            }
            var parentProblemClass =
                this.$store.state.global.problemClassMap[
                    this.$store.state.global.problemClassMap[draftProblem.problemClassId].parent_problem_class_id
                ];
            if(parentProblemClass.problem_class_name != '工程亮点') {
                if(draftProblem.repair == null || draftProblem.repair == '') {
                    this.$f7.dialog.alert('', '请选择整改人!');
                    return;
                }
                if(draftProblem.reinspects.length == 0) {
                    this.$f7.dialog.alert('', '请选择复验人!');
                    return;
                }
            }
            this.problemRegist(draftProblem, true);
        },
        reloadProblemList() {
            var self = this;
            self.$f7.preloader.show();
            new Promise((resolve, reject) => {
            	if(Common.isOnline()) {
            		let promises = [];
                    let sql = "delete from tb_checkquality_problem where batch_id = ?";
            		promises.push(Common.executeSql(sql, [self.batchId]).then(() => {
                    	return request({
                            url: '/api/checkQualityProblem/findByBatchId',
                            methos: 'get',
                            params: {
                                batchId: self.batchId
                            }
                        });
            		}).then((data) => {
            			var elements = data.list;
            			return db.insert('tb_checkquality_problem', elements);
            		}).then(() => {
            			return Promise.resolve();
            		}).catch(error => {
            			console.error(error);
            			return Promise.resolve();
            		}));

                    sql = "\
                        delete from tb_checkquality_repair \
                        where checkquality_problem_id in ( \
                            select id \
                            from tb_checkquality_problem \
                            where batch_id = ? \
                        ) \
                    ";
            		promises.push(Common.executeSql(sql, [self.batchId]).then(() => {
                    	return request({
                            url: '/api/checkQualityRepair/findByBatchId',
                            methos: 'get',
                            params: {
                                batchId: self.batchId
                            }
                        });
            		}).then((data) => {
            			var elements = data.list;
            			return db.insert('tb_checkquality_repair', elements);
            		}).then(() => {
            			return Promise.resolve();
            		}).catch(error => {
            			console.error(error);
            			return Promise.resolve();
            		}));

                    sql = "\
                        delete from tb_checkquality_reinspect \
                        where checkquality_problem_id in ( \
                            select id \
                            from tb_checkquality_problem \
                            where batch_id = ? \
                        ) \
                    ";
            		promises.push(Common.executeSql(sql, [self.batchId]).then(() => {
                    	return request({
                            url: '/api/checkQualityReinspect/findByBatchId',
                            methos: 'get',
                            params: {
                                batchId: self.batchId
                            }
                        });
            		}).then((data) => {
            			var elements = data.list;
            			return db.insert('tb_checkquality_reinspect', elements);
            		}).then(() => {
            			return Promise.resolve();
            		}).catch(error => {
            			console.error(error);
            			return Promise.resolve();
            		}));
            		
            		Promise.all(promises).then(() => {
            			resolve();
            		});
            		
            	} else {
            		resolve();
            	}
            }).then(() => {
                let sql = 
                    "select e.bid_section_id, b.*, c.id as checkquality_repair_id, c.repair, " +
                    "   case when GROUP_CONCAT(distinct d.reinspect) is null then '[]' else '[' || GROUP_CONCAT(distinct '\"' || d.reinspect || '\"') || ']' end as reinspect, " +
                    "   case when GROUP_CONCAT(distinct d.reinspect) is null then '[]' else '[' || GROUP_CONCAT(distinct '\"' || d.id || '\"') || ']' end as checkquality_reinspect_id " +
                    "from tb_checkquality_problem b " +
                    "left join tb_checkquality_repair c on b.id = c.checkquality_problem_id " +
                    "left join tb_checkquality_reinspect d ON b.id = d.checkquality_problem_id " +
                    "left join tb_building e on e.id = b.building_id " +
                    "where b.batch_id in (select a.id from tb_checkquality_batch a where a.id = '" + self.batchId + "') " + 
                    "and c.child_checkquality_repair_id is null " + 
                    "GROUP BY b.id " +
                    "order by b.regist_date desc";;
                 return Common.executeSql(sql, []);
            }).then((result) => {
                let rs = result.rs;
                let submitedProblemList = [];
                for(var i = 0; i < rs.rows.length; i++) {
                    var row = rs.rows.item(i);
                    submitedProblemList.push(
                        self.convertLocaleCheckSubmited(row)
                    );
                }
                self.submitedProblemList = submitedProblemList;
                
                let sql = "\
                    select * from tmp_locale_check_checkquality_problem_regist t \
                    where t.batch_id = '" + self.batchId + "' \
                ";
                return Common.executeSql(sql, []);
            }).then((result) => {
            	let rs = result.rs;
                let draftProblemList = [];
            	for(var i = 0; i < rs.rows.length; i++) {
                    var row = rs.rows.item(i);
                    draftProblemList.push(
                        self.convertLocaleCheckDraft(row)
                    );
                }
            	self.draftProblemList = draftProblemList;
                self.$f7.preloader.hide();
            }).catch((error) => {
            	console.error(error);
                self.$f7.preloader.hide();
            });
        }
    },
    computed: {
        
    },
    watch: {
    	'batchId': function(newVal, oldVal) {
    		var self = this;
    		if(newVal == null) {
    			clearStore(keys.localeCheckBatchIdKey);
    			self.batch = null;
    		} else {
    			setStore(keys.localeCheckBatchIdKey, this.batchId);
    			let sql = " \
    			    select t.*, p.ccs \
    			    from tb_checkquality_batch t \
    			    left join ( \
    			    	select batch_id,  \
    			    	case when GROUP_CONCAT(user_id) is null then '[]' else '[' || GROUP_CONCAT('\"' || user_id || '\"') || ']' end as ccs \
    			    	from tb_batch_cc \
    			    	where batch_id = ? \
    			    	group by batch_id \
    			    ) p \
    			    on t.id = p.batch_id \
    			    where t.id = ? \
    			";
        		Common.executeSql(sql, [self.batchId, self.batchId]).then((result) => {
        			let rs = result.rs;
               		let row = rs.rows.item(0);
                	let batch = {};
                    batch.id = row.id;
                    batch.name = row.name;
                    batch.repairDeadline = row.repair_deadline;
                    batch.bidSectionId = row.bid_section_id;
                    batch.inChargeBy = row.in_charge_by;
                    batch.ccs = row.ccs == null ? [] : Common.strToJson(row.ccs);
                    self.batch = batch;
                }).catch(error => {
                	console.error(error);
                });
        		this.reloadProblemList();
    		}
    	}
    },
    created: function() {
        
    },
    mounted: function() {
        var self = this;
        var ptrContent = self.Dom7('.ptr-content');
        ptrContent.on('ptr:refresh', function(e) {
            e.detail();
            self.reloadProblemList();
        });
    },
}
</script>

<style scoped>

</style>